<template>
	<view class="page">
		<view class="title-bar">账户登录</view>
		<image class="avatar"
			src="https://store-profit-system.oss-cn-shanghai.aliyuncs.com/wisdomClubApp/loginLogo.png" />

		<form @submit.prevent="handleLogin()">
			<template v-if="loginMethod === 'code'">
				<view class="form-group">
					<label for="phoneNumber">手机号</label>
					<input id="phoneNumber" v-model="phoneNumber" type="text" placeholder="请输入手机号" />
				</view>
				<view class="form-group">
					<label for="verificationCode">验证码</label>
					<input id="verificationCode" v-model="verificationCode" type="text" placeholder="请输入验证码" />
					<view @click="getCode" :class="{'disabled': isCounting}" class="getCode">{{ countdownText }}</view>
				</view>
			</template>

			<template v-else>
				<view class="form-group">
					<label for="account">账号</label>
					<input id="account" v-model="phoneNumber" type="text" placeholder="请输入账号" />
				</view>
				<view class="form-group">
					<label for="password">密码</label>
					<input id="password" v-model="password" type="password" placeholder="请输入密码" />
				</view>
			</template>

			<!-- Links to toggle between login methods -->
			<view class="toggle-login-methods">
				<navigator v-if="loginMethod === 'code'" url="javascript:void(0);" @click="loginMethod = 'password'"
					hover-class="none">已有账号？立即登录</navigator>
				<navigator v-else url="javascript:void(0);" @click="loginMethod = 'code'" hover-class="none">手机验证码登录
				</navigator>
			</view>

			<view class="btn-wrapper">
				<button class="bg-green btn1" form-type="submit">登录</button>
			</view>
		</form>
	</view>
</template>

<script>
	import {
		getCodeLogin,
		codeLogin,
		Login
	} from '@/api/login.js';
	import {
		getUserInfo,
		getSilent
	} from '@/api/user.js';

	export default {
		data() {
			return {
				loginMethod: 'code', // Default to code login
				phoneNumber: '',
				verificationCode: '',
				password: '',
				isCounting: false,
				countdownTime: 60,
				countdownText: '获取验证码',
			};
		},
		methods: {
			validatePhoneNumber() {
				const phoneRegex = /^1[3456789]\d{9}$/;
				return phoneRegex.test(this.phoneNumber);
			},
			getCode() {
				if (!this.validatePhoneNumber()) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				if (this.isCounting) return;

				getCodeLogin({
					phoneNumber: this.phoneNumber
				}).then(() => {
					this.startCountdown();
				}).catch(error => {
					console.error('获取验证码失败:', error);
					uni.showToast({
						title: '获取验证码失败',
						icon: 'none'
					});
				});
			},
			startCountdown() {
				this.isCounting = true;
				let timer = setInterval(() => {
					this.countdownTime--;
					this.countdownText = `${this.countdownTime}s后重新获取`;
					if (this.countdownTime <= 0) {
						clearInterval(timer);
						this.isCounting = false;
						this.countdownTime = 60;
						this.countdownText = '获取验证码';
					}
				}, 1000);
			},
			async handleLogin() {
				if (this.loginMethod == 'code') {
					if (!this.validatePhoneNumber()) {
						uni.showToast({
							title: '请输入正确的手机号',
							icon: 'none'
						});
						return;
					}

					try {
						const response = await codeLogin({
							phoneNumber: this.phoneNumber,
							verificationCode: this.verificationCode
						});

						if (response.code == 200) {
							this.$store.commit("LOGIN", {
								token: response.msg
							});
							localStorage.setItem('token', response.msg);
							getUserInfo().then(res => {
								const pid = uni.getStorageSync('pid') || '-1';
								getSilent(0, pid, res.data.uid).then(res => {
									window.location.replace(res.data.authUrl);
									// uni.switchTab({
									// 	url: '/pages/platform/index'
									// });
								});
							})
						}
					} catch (error) {
						console.error('验证码登录失败:', error);
					}
				} else {
					try {
						const response = await Login({
							phoneNumber: this.phoneNumber,
							password: this.password
						});
						if (response.code == 200) {
							this.$store.commit("LOGIN", {
								token: response.msg
							});
							localStorage.setItem('token', response.msg);
							getUserInfo().then(res => {
								const pid = uni.getStorageSync('pid') || '-1';
								getSilent(0, pid, res.data.uid).then(res => {
									window.location.replace(res.data.authUrl);
									// uni.switchTab({
									// 	url: '/pages/platform/index'
									// });
								});
							})
						}
					} catch (error) {
						console.error('账号密码登录失败:', error);
					}
				}
			}
		}
	};
</script>

<style lang="scss">
	.page {
		background: #fff;
		min-height: 100vh;
		background-image: url('https://store-profit-system.oss-cn-shanghai.aliyuncs.com/wisdomClubApp/loginBag.png');
		background-size: cover;
		background-position: center;
	}

	.avatar {
		width: 400rpx;
		height: 160rpx;
		margin-top: 100rpx;
		margin: 100rpx 0rpx 100rpx 22%;
	}

	.title-bar {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
		height: 88rpx;
		padding-top: 20rpx;
	}

	.logo {
		width: 400rpx;
		height: auto;
		max-width: 100%;
		margin: 80rpx auto 40rpx;
		display: block;
	}

	.form-group {
		margin-bottom: 30rpx;
		position: relative;
		margin: 0rpx 30rpx;
		margin-top: 20rpx;

		label {
			display: block;
			margin-bottom: 10rpx;
			font-size: 28rpx;
			color: #333;
		}

		input {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			border: 1px solid #ccc;
			border-radius: 8rpx;
			padding: 0 20rpx;
			box-sizing: border-box;
			font-size: 28rpx;
		}

		.getCode {
			position: absolute;
			right: 20rpx;
			top: 66%;
			transform: translateY(-50%);
			font-size: 24rpx;
			color: #1D85E1;
			cursor: pointer;
			user-select: none;

			&.disabled {
				color: #ccc;
				cursor: not-allowed;
			}
		}
	}

	.btn-wrapper {
		margin-top: 60rpx;
		padding: 0 66rpx;

		button {
			width: 100%;
			height: 86rpx;
			line-height: 86rpx;
			border-radius: 120rpx;
			font-size: 30rpx;
			color: #fff;
			background-color: #1D85E1;
			border: none;
			outline: none;
			cursor: pointer;
			transition: background-color 0.3s;

			&:active {
				background-color: darken(#1D85E1, 10%);
			}
		}

		.buttomNavigator {
			text-align: center;
			margin-top: 20rpx;
			font-size: 24rpx;
			color: #7AAD5B;
		}
	}

	.toggle-login-methods {
		margin-top: 60rpx;
		text-align: center;

		navigator {
			color: #1D85E1;
			font-size: 24rpx;
		}
	}
</style>